package com.sport.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(SaTokenConfigure.class);

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，校验规则为 StpUtil.checkLogin() 登录校验。
        registry.addInterceptor(new SaInterceptor(handle -> {
            String requestPath = SaHolder.getRequest().getRequestPath();
//            logger.info("请求路径: {}", requestPath);

                    SaRouter.match("/**")
                            .notMatch("/favicon.ico","/doc.html","/webjars/**","/v3/api-docs/**","/login/simulateUserScan")
                            .check(StpUtil::checkLogin);
                }))
                .addPathPatterns("/**")
                .excludePathPatterns("/user/doLogin",
                        "/login/simulateUserScan");
    }

    @Bean
    public SaServletFilter saServletFilter() {
        return new SaServletFilter()
                .setBeforeAuth(obj -> {
                    SaHolder.getResponse()
                            .setHeader("Access-Control-Allow-Origin", "*")
                            .setHeader("Access-Control-Allow-Headers", "*")
                            .setHeader("Access-Control-Allow-Methods", "*")
                            .setHeader("Access-Control-Max-Age", "3600")
                            .setHeader("Access-Control-Expose-Headers", "x-uuid");
                    SaRouter.match(SaHttpMethod.OPTIONS).back();
                });
    }
}
